package org.example.memora.task;

import lombok.extern.slf4j.Slf4j;
import org.example.memora.entity.CommentLikeStat;
import org.example.memora.mapper.CommentLikeStatMapper;
import org.example.memora.mapper.PostMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.util.Set;

@Component
@Slf4j
public class CommentLikeSyncTask {

    // LIKE_TASK_TIME 例如 60000 毫秒
    private static final long LIKE_TASK_TIME = 6000;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private CommentLikeStatMapper commentLikeStatMapper;
    @Autowired
    private PostMapper postMapper;

    // 每固定时间同步一次 Redis 中的评论点赞计数
    @Scheduled(fixedDelay = LIKE_TASK_TIME)
    @Transactional
    public void syncLikeCounts() {
        Set<String> keys = redisTemplate.keys("comment:like:count:*");
        if (keys == null || keys.isEmpty()) {
            return;
        }
        for (String key : keys) {
            try {
                // 从 key 中解析出 commentId
                String commentId = key.substring("comment:like:count:".length());
                String countStr = redisTemplate.opsForValue().get(key);
                int increment = (countStr != null) ? Integer.parseInt(countStr) : 0;
                if (increment <= 0) {
                    continue;
                }
                // 查询数据库中是否已有统计记录
                CommentLikeStat stat = commentLikeStatMapper.selectByPrimaryKey(commentId);
                if (stat == null) {
                    // 如果没有记录，则创建新的统计记录
                    stat = new CommentLikeStat();
                    stat.setCommentId(commentId);
                    stat.setLikeCount(increment);
                    stat.setUpdatedAt(Instant.now());
                    commentLikeStatMapper.insert(stat);
                } else {
                    // 如果存在记录，则累加更新
                    stat.setLikeCount(stat.getLikeCount() + increment);
                    stat.setUpdatedAt(Instant.now());
                    commentLikeStatMapper.updateByPrimaryKey(stat);
                }
                // 同步成功后删除 Redis 中对应的计数 key
                redisTemplate.delete(key);
                log.info("更新数据库评论点赞数，commentId: {}", commentId);
            } catch (Exception e) {
                log.error("同步评论点赞数出错", e);
            }
        }
    }
}

